package com.twu.biblioteca.model.users;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * Created with IntelliJ IDEA.
 * User: cschlumb
 * Date: 09/08/2013
 * Time: 14:23
 * To change this template use File | Settings | File Templates.
 */
public class SecurityUtils {

    public static byte[] getRandomSalt() {
        SecureRandom random = new SecureRandom();
        byte bytes[] = new byte[20];
        random.nextBytes(bytes);
        return bytes;
    }

    public static byte[] hashPassword(String password, byte[] salt) {

        byte[] plaintextPassword = password.getBytes();

        byte[] saltedPassword = new byte[plaintextPassword.length + salt.length];
        System.arraycopy(plaintextPassword, 0, saltedPassword, 0, plaintextPassword.length);
        System.arraycopy(salt, 0, saltedPassword, plaintextPassword.length, salt.length);

        try {
            return MessageDigest.getInstance("SHA-256").digest(saltedPassword);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException();
        }
    }

}
